package top.jandmla.excel.config.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import top.jandmla.excel.bean.Menu;
import top.jandmla.excel.pojo.RolePojo;
import top.jandmla.excel.pojo.UserPojo;
import top.jandmla.excel.service.UserService;


public class UserRealm  extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        UserPojo user = (UserPojo) principalCollection.getPrimaryPrincipal();

        for (RolePojo role : user.getRoleList()) {
            info.addRole(role.getRoleName());
            for (Menu menu : role.getMenusList()) {
                info.addStringPermission(menu.getPermit());
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        UserPojo user = userService.getPojoUser(userToken.getUsername());

        if (user == null){
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),"userRealm");
    }
}
